#pragma once

#include<iostream>
#include<pthread.h>

using namespace std;

class Thread
{

public:
    typedef void(*func_t)(void *);
    typedef enum
    {
        NEW = 0,
        RUNING,
        EXITED
    } ThreadStatus;
    Thread(int nume,func_t func,void* args)
    :_tid(0),_status(NEW),_func(func),_args(args)
    {
        char name[64] ;
        snprintf(name,sizeof(name),"thread-%d",nume+1);
        _name = name;

    }

    int status(){return _status;}
    string threadname() { return _name;}
    pthread_t threadid()
    {
        if(_status == RUNING)
        {
            return _tid;
        }
        else{
            return 0;
        }
    }

    // 是不是类的成员函数，而类的成员函数，具有默认参数this,需要static
    // 但是会有新的问题：static成员函数，无法直接访问类属性和其他成员函数,解决方法：用this传入args
    static void *runHelper(void *args)
    {
        Thread *ts = static_cast<Thread *>(args); //拿到当前对象
        //cout<<ts->_name<<endl;
        (*ts)();
        return nullptr;
    }

    void operator()()
    {
        if(_func != nullptr) _func(_args);
    }

    void run()
    {
        int n = pthread_create(&_tid,nullptr,runHelper,this);//这里runHelper的参数传入this指针
        if(n != 0) exit(1);                                  //为了解决static void *runHelper(void *args)
        _status = RUNING;                                    //静态函数没有this指针，不能访问成员函数的问题
    }
    void join()
    {
        int n = pthread_join(_tid, nullptr);
        if( n != 0)
        {
            std::cerr << "main thread join thread " << _name << " error" << std::endl;
            return;
        }
        _status = EXITED;
    }
    ~Thread()
    {

    }

private:
    pthread_t _tid;
    string _name;
    func_t _func;
    void *_args;
    ThreadStatus _status;
    

};

